#include "Operator.h"


Operator::Operator(std::string name, unsigned int priority, Node * parent)
{
	this->_name = name;
	this->_priority = priority;
	this->_parent = parent;
}

void Operator::print(std::string& tree)
{
	tree.append(this->_name);
	for (unsigned int i=0; i < this->countChildren(); i++)
	{
		tree.append("(");
		this->getChild(i)->print(tree);
		tree.append(")");
	}
}

void Operator::clone(Node** node)
{
	(*node) = new Operator(this->_name, this->_priority, this->_parent);
	if (this->countChildren() > 0)
	{
		for (unsigned int i=0; i < this->countChildren(); i++)
		{
			Node* ch;
			this->getChild(i)->clone(&ch);
			(*node)->addChild(ch);
		}
	}
}

Operator::~Operator(void)
{
}

int Operator::getType() const
{
	return OPERATOR;
}

bool Operator::checkNode(std::vector<Variables> & vars, const Node* goal)
{
	std::vector<Variables> clone;
	for(int i=0;i<vars.size();i++)
	{
		clone.push_back(vars[i]);
	}
	if (this->_name.compare(",") == 0)
	{
		return this->getChild(0)->checkNode(clone, goal) && this->getChild(1)->checkNode(clone, goal);
	}
	else if (this->_name.compare(":-") == 0)
	{
		bool isCorrect = this->getChild(0)->checkNode(clone, goal);
		if(isCorrect)
		{
			std::vector<Variables> tmp;
			for(int i=vars.size();i<clone.size();i++)
			{
				tmp.push_back(clone[i]);
			}
			if(this->getChild(1)->checkNode(tmp, goal))
			{
				for(int i=0;i<tmp.size();i++)
				{
					if(!(tmp[i] == clone[vars.size()+i]))
					{
						for (int j = 0; j < vars.size(); j++)
						{
							if (vars[j].getName().compare(tmp[i].getName()) == 0)
							{
								vars[j].setValue(tmp[i].getValue());
								break;
							}
						}
					}
				}
			}
		}
		return isCorrect;
	}
	else if (this->_name.compare(";") == 0)
	{
		bool isCorrect = this->getChild(0)->checkNode(clone, goal) || this->getChild(1)->checkNode(clone, goal);
		if(isCorrect)
		{
			vars=clone;
		}
		return isCorrect;
	}
	return false;
}

std::string Operator::getValue(std::vector<Variables>)
{
	return "";
}